<script setup lang="ts">
import { getCouponPackListApi, getFoodMsgApi, postCollectApi } from '@/services/eat'
import { getBannerListApi, getMachineDataApi } from '@/services/home'
import {
  useDeviceStore,
  useMemberStore,
  usePhoneStore,
  useShoppingCartStore,
  usePagesMachineIdStore,
  useLocationStore,
} from '@/stores'
import type { cartDataType } from '@/types/component'
import type { spotItem } from '@/types/eat'
import { onLoad, onReady, onShow, onUnload } from '@dcloudio/uni-app'
import { ref, computed, watch, inject } from 'vue'
import {
  PageSkip,
  SwitchingDistance,
  Toast,
  MyShowModal,
  getExternalSkipMiniApp,
} from '@/utils/tools'
import useQuery from '@/hooks/useQuery'

const { getQueryParams } = useQuery()

const locationStore = useLocationStore()
const memberStore = useMemberStore()
const phoneStore = usePhoneStore()
const shoppingCartStore = useShoppingCartStore()
const deviceStore = useDeviceStore()
const pagesMachineId = usePagesMachineIdStore()
const cartFlag = ref(false) // 用来判断购物车是否关闭
const { loginPromise } = <{ loginPromise: Promise<unknown> }>inject('globalData')

onLoad(async (ev) => {
  console.log('onLoad', ev)
  // 判断是否是从吃饭页面登录
  ev?.machineId ? pagesMachineId.setPagesMachineId(ev.machineId) : null

  // 判断是否是设备扫码登录的
  if (ev?.q) {
    getExternalSkipMiniApp(ev)
    const machineId = getQueryParams()?.machineId
    machineId ? pagesMachineId.setPagesMachineId(machineId) : null
    loginPromise.then(() => {
      getspotList()
    })
    return
  }
  console.log(phoneStore.phoneInfo)
  // console.log(deviceStore?.deviceInfo)
  loginPromise.then(() => {
    getspotList()
  })
})
// 页面变化就刷新套餐列表
onShow(() => {
  if (memberStore.token && !isWatchShoppingCart.value) {
    getShoppingCartList()
  }
  loginPromise.then(() => {
    getFoodList()
    getCouponPackList()
    getBannerList()
  })
})

let machineList = ref<spotItem[]>()
/** 获取设备列表信息 */
const getspotList = async () => {
  console.log('==========================================')
  console.log('pagesMachineId', pagesMachineId.pagesMachineId)
  try {
    const res = await getMachineDataApi({
      machineId: pagesMachineId.pagesMachineId || null,
      clientId: memberStore.userInfo?.id || '',
      longitude: locationStore.location!.longitude,
      latitude: locationStore.location!.latitude,
      pageNum: 1,
      pageSize: 3,
    })
    machineList.value = res?.data
    let machineItem = res.data?.find((i: any) => pagesMachineId.pagesMachineId === i.machineId)
    machineItem ? deviceStore.setDeviceInfo(machineItem) : null
  } catch (error) {
    console.log('catch', error)
  }
}

onReady(() => {
  if (pagesMachineId.pagesMachineId) return
  setTimeout(() => {
    popup.value?.open() // 在视图加载完成后就 打开选择设备的弹窗
  }, 500)
})

/** 点击选择设备 */
const onClick = (e: any) => {
  deviceStore.setDeviceInfo(e)
  PageSkip('/pages/eat/eat', 'switchTab')
}
/**
 * * 设备弹出层的收藏按钮 用户未登录，就弹出用户登录弹窗
 */
const collectFn = async (e: any) => {
  // console.log(e)
  if (memberStore.userInfo) {
    const parm = {
      clientId: memberStore.userInfo.id,
      machineId: e.machineId,
    }
    Toast(e.isBookmark ? '取消收藏' : '已收藏')
    await postCollectApi(parm)
    getspotList()
  } else {
    popupRef.value.open()
  }
}
/** 从本地缓存获取设备收藏 icon */
const choiceIcon = computed(() => {
  return deviceStore.deviceInfo?.isBookmark ? 'icon_XingX_1' : 'icon_XingX_0'
})
/** 判断列表是否显示 */
const handleShow = computed(() => {
  return searchData.value.length > 0 || couponPackList.value.length > 0
})

/** 页面的收藏 用户未登录，就弹出用户登录弹窗 */
const onCollect = () => {
  if (memberStore.token) {
    deviceStore.deviceInfo!.isBookmark = !deviceStore.deviceInfo?.isBookmark
    getCollect()
  } else {
    popupRef.value?.open()
  }
}

/**活跃度接口 */
const addActivityDegree = () => {
  try {
    postActivityDegreeApi({
      machineId: deviceStore.deviceInfo!.machineId,
      temporarySign: memberStore.token ? null : phoneStore.phoneInfo!.deviceId!,
    })
  } catch (error) {
    console.log(error)
  }
}
/** 收藏接口请求 */
const getCollect = async () => {
  const objItem = {
    clientId: memberStore.userInfo!.id,
    machineId: deviceStore.deviceInfo!.machineId,
  }
  await postCollectApi(objItem)
  Toast(deviceStore.deviceInfo?.isBookmark ? '已收藏' : '取消收藏')
  addActivityDegree()
}
const awaitNum = ref(0)
const searchData = ref<any[]>([])
/** 获取餐品信息列表 */
const getFoodList = async () => {
  try {
    const res = await getFoodMsgApi({
      machineId: deviceStore.deviceInfo!.machineId,
      pageNum: 1,
      pageSize: 50,
    })
    awaitNum.value = res?.data?.awaitNum
    searchData.value = res?.data?.list || []
    // console.log('searchData.value', searchData.value)
  } catch (error) {
    console.log(error)
  }
}
/** 监听套餐列表，列表产生了改变，就遍历购物车列表，判断套餐id是否相同，相同就修改套餐库存 */
watch(
  () => searchData.value,
  (newVal) => {
    if (!shoppingCartStore.shoppingCartInfo.length || !newVal.length) {
      console.log('购物车为空，餐品列表为空')
      return
    }
    const indicesToDelete: number[] = []
    for (let i = 0; i < shoppingCartStore.shoppingCartInfo.length; i++) {
      const isFindItem = newVal.find((item) => {
        console.log(item.comboId, shoppingCartStore.shoppingCartInfo[i].packageId)
        return item.comboId === shoppingCartStore.shoppingCartInfo[i].packageId
      })
      console.log({ isFindItem })
      if (isFindItem) {
        const obj = {
          packageName: isFindItem.appletComboInfoDto!.comboName,
          thumbUrl: isFindItem.appletComboInfoDto!.thumbUrl,
          applietAmount: isFindItem.appletComboInfoDto!.marketing.applietAmount,
          deviceAmount: isFindItem.appletComboInfoDto!.marketing.deviceAmount,
          inventory: isFindItem.stocks,
          discountedAfterPrice: isFindItem.appletComboInfoDto!.marketing.discountedAfterPrice,
          spicy: isFindItem.appletComboInfoDto.tastes?.spicy,
        }
        shoppingCartStore.shoppingCartInfo[i] = {
          ...shoppingCartStore.shoppingCartInfo[i],
          ...obj,
        }
        if (shoppingCartStore.shoppingCartInfo[i].count > isFindItem.stocks) {
          shoppingCartStore.shoppingCartInfo[i].count = isFindItem.stocks
        }
      } else {
        indicesToDelete.push(i)
      }
    }
    // console.log('进入监听套餐列表', indicesToDelete)
    // 删除不需要的商品
    for (let j = indicesToDelete.length - 1; j >= 0; j--) {
      shoppingCartStore.shoppingCartInfo.splice(indicesToDelete[j], 1)
    }
    // console.log(shoppingCartStore.shoppingCartInfo)
    // 过滤掉库存为0的套餐
    shoppingCartStore.shoppingCartInfo = shoppingCartStore.shoppingCartInfo.filter(
      (item) => item.count > 0,
    )
  },
  { deep: true, immediate: true },
)

// 获取礼包商品列表
const couponPackList = ref<any[]>([])
const getCouponPackList = async () => {
  try {
    const res = await getCouponPackListApi()
    couponPackList.value = res?.data || []
    // couponPackList.value[0].declare =
    //   '<p>1．霸王免单优惠券；<br/>2．部分订单商品金额满12元可用；<br/>3．有效期至2024—11一24 23：59：59；<br/>4．可使用营业点：仅限部分营业点可用；<br/>5．优惠券仅原价购买时可用。</p><p>1．霸王免单优惠券；<br/>2．部分订单商品金额满12元可用；<br/>3．有效期至2024—11一24 23：59：59；<br/>4．可使用营业点：仅限部分营业点可用；<br/>5．优惠券仅原价购买时可用。</p>'
  } catch (error) {
    console.log(error)
  }
}

/** 设备 弹出层  */
const popup = ref<{
  open: () => void
  close: () => void
}>()
const isIconPopup = ref(false)
/**
 * * 点击 icon 悬浮球 展开购物车弹窗
 */
const onUnfold = () => {
  if (
    cartFlag.value === true &&
    shoppingCartStore.shoppingCartInfo.length > 0 &&
    isIconPopup.value === false
  ) {
    cartPopup.value?.open()
    isIconPopup.value = true
  } else if (
    cartFlag.value === true &&
    shoppingCartStore.shoppingCartInfo.length > 0 &&
    isIconPopup.value === true
  ) {
    cartPopup.value?.close()
    isIconPopup.value = false
  } else if (cartFlag.value === true && shoppingCartStore.shoppingCartInfo.length <= 0) {
    Toast('请选择商品！')
  } else {
    cartFlag.value = true
  }
}
// 悬浮窗上的圆角数字
const com = computed(() => {
  let sum = ref(0)
  shoppingCartStore.shoppingCartInfo?.forEach((item) => {
    sum.value = sum.value + item.count
  })
  return sum.value
})
// 总价
const totalPrice = computed(() => {
  return shoppingCartStore.shoppingCartInfo?.reduce((prev: number, next: cartDataType) => {
    return prev + next.count * parseFloat(next.deviceAmount)
  }, 0)
})

// 购物车的 弹出层 cartPopup
const cartPopup = ref<{
  open: () => void
  close: () => void
}>()

/** 滑动关闭购物车 当购物车数组有长度的时候就 ，不关闭购物车 */
const scroll = () => {
  if (shoppingCartStore.shoppingCartInfo?.length) return
  cartFlag.value = false
}
/**
 * 点击去结算按钮 跳转到结算页面
 * 购物车没有值的时候，return出去，不进行跳转
 */
const goToPay = (obj?: any) => {
  if (!obj) {
    if (!shoppingCartStore.shoppingCartInfo?.length) return
    if (memberStore.userInfo && shoppingCartStore.shoppingCartInfo?.length > 0) {
      if (
        deviceStore.deviceInfo &&
        +deviceStore.deviceInfo?.distanceCenterPoint > 1000 &&
        +deviceStore.deviceInfo?.distanceCenterPoint < 5000
      ) {
        MyShowModal('您当前所在位置距离该设备较远，是否继续下单？').then(({ confirm }) => {
          if (confirm) {
            cartPopup.value?.close() // 关闭购物弹出层
            isIconPopup.value = false // 关闭购物车弹出层判断得值
            PageSkip('/pagesEat/billingPage/billingPage') // 进行跳转
          }
        })
      } else if (
        deviceStore.deviceInfo?.distanceCenterPoint &&
        +deviceStore.deviceInfo?.distanceCenterPoint > 5000
      ) {
        Toast('当前所在位置离设备较远，无法下单！')
      } else {
        cartPopup.value?.close() // 关闭购物弹出层
        isIconPopup.value = false // 关闭购物车弹出层判断得值
        PageSkip('/pagesEat/billingPage/billingPage') // 进行跳转
      }
    } else {
      popupRef.value.open()
    }
  } else {
    if (memberStore.userInfo && obj) {
      uni.navigateTo({
        url:
          '/pagesEat/billingPage/billingPage?type=couponPack&couponPackInfo=' + JSON.stringify(obj),
      }) // 进行跳转
      return
    } else {
      popupRef.value.open()
    }
  }
}
/**
 * 登录弹出层实例
 */
const popupRef = ref()

let popupFlag = ref(false) // 购物车是否显示的值
/**
 * * 点击清空，弹出二次确认框, 清空购物车
 */
const onCloseCart = () => {
  popupFlag.value = true // 改变购物车显示的值

  MyShowModal('是否清空购物车？').then(({ confirm }) => {
    if (confirm) {
      shoppingCartStore.clearShoppingCartInfo()
      cartPopup.value?.close()
    }
  })
}

/**
 *  点击删除某一样餐品
 */
const onOpen = (id: string) => {
  popupFlag.value = false // 改变购物车显示的值

  MyShowModal('确认删除该商品吗？').then(({ confirm }) => {
    if (confirm) {
      shoppingCartStore.shoppingCartInfo.forEach((item, index) => {
        // 进行对比餐品 id 和本地缓存的购物车里面的 id 是否一样
        if (item.packageId === id) {
          shoppingCartStore.shoppingCartInfo.splice(index, 1)
          // 判断本地缓存的 购物车数组是否还有数据，没有数据就把购物车弹出层关闭
          if (shoppingCartStore.shoppingCartInfo.length <= 0) {
            cartPopup.value?.close() // 关闭购物车弹出层
          }
        }
      })
    }
  })
}
import { postOrderSettlementApi } from '@/services/eat'

const discountMoney = ref<number>(0)
/** 刷新购物车数据 */
const getShoppingCartList = async () => {
  if (!shoppingCartStore.shoppingCartInfo.length) return
  const shoppingCartList = shoppingCartStore.shoppingCartInfo.map((item) => {
    return {
      machineId: deviceStore.deviceInfo!.machineId,
      packageId: item.packageId,
      packageName: item.packageName,
      quantity: item.count,
    }
  })
  const res = await postOrderSettlementApi({
    machineId: deviceStore.deviceInfo!.machineId,
    machineName: deviceStore.deviceInfo!.machineName,
    shoppingCartList,
  })
  discountMoney.value = res.data.discountMoney || 0
}
const isWatchShoppingCart = ref(false)
watch(
  () => shoppingCartStore.shoppingCartInfo,
  async (newVal) => {
    console.log('购物车数据', newVal)
    cartFlag.value = newVal.length > 0 // 监听购物车是否有数据，有就展开购物车悬浮窗
    if (memberStore.token && newVal.length) {
      isWatchShoppingCart.value = true
      try {
        await getShoppingCartList()
      } finally {
        isWatchShoppingCart.value = false
      }
    }
  },
  {
    deep: true,
    immediate: true,
  },
)

// 调用小程序的分享，以及监听小程序分享
import useMiniShare from '@/hooks/useMiniShare'
const { isShareFriends, onShareAppMessage, setupOnShareAppMessage } = useMiniShare()
isShareFriends()
onShareAppMessage
onShow(() => {
  const shareParams = {
    path: `/pages/eat/eat?machineId=${deviceStore.deviceInfo?.machineId}&machineName=${deviceStore.deviceInfo?.machineName}&positionAddr=${deviceStore.deviceInfo?.positionAddr}&businessStatus=${deviceStore.deviceInfo?.businessStatus}&saleBeginTime=${deviceStore.deviceInfo?.saleBeginTime}&saleEndTime=${deviceStore.deviceInfo?.saleEndTime}`,
    title: deviceStore.deviceInfo?.machineName,
  }
  setupOnShareAppMessage(shareParams)
  // console.log(shareParams)
})

const imageList = ref([
  { resourceUrl: 'https://yuefanpai.oss-cn-hangzhou.aliyuncs.com/miniapp/chifan.png' },
  { resourceUrl: 'https://yuefanpai.oss-cn-hangzhou.aliyuncs.com/miniapp/chifan.png' },
  { resourceUrl: 'https://yuefanpai.oss-cn-hangzhou.aliyuncs.com/miniapp/chifan.png' },
])

/**获取 banner 列表 */
const getBannerList = async () => {
  try {
    const res = await getBannerListApi(locationStore.location?.cityName)
    console.log('banner', res)
    if (res.data.eatBanners) {
      imageList.value = res.data?.eatBanners?.map((item: any) => {
        return {
          ...item,
          resourceUrl: item.img,
        }
      })
    }
  } catch (error) {}
}

// 监听本地缓存的设备信息是否变化，根据变化重新去获取菜品列表、改变分享链接的设备id
watch(
  () => deviceStore.deviceInfo?.machineId,
  (newVal, oldVal) => {
    if (newVal !== oldVal) {
      getFoodList()
      // getCouponPackList() // 兼容设备扫码进入后触发获取礼包列表
      // getBannerList() // 兼容设备扫码进入后触发获取轮播图
    }
  },
  {
    immediate: true,
  },
)

import { postActivityDegreeApi } from '@/services/component'

/**
 * * 跳转到地图界面
 */
const skipMapPage = () => {
  PageSkip('/pagesEat/deviceSearch/deviceSearch')
}

/**设置轮询 */
const polling = setInterval(() => {
  if (pagesMachineId.pagesMachineId) return clearInterval(polling)
  getspotList()
}, 3000)
onUnload(() => {
  clearInterval(polling)
})

/**设备弹出层触发 */
const devicePopupChange = (e: any) => {
  !e.show && clearInterval(polling)
}

/** 触发规则组件 */
const rulePopupObj = ref<any>({})
const rulePopupRef = ref()
const triggerRules = (obj: any) => {
  rulePopupObj.value = obj
  rulePopupRef?.value.popupOpen()
}
const getCityName = () => {
  try {
    console.log('getCityName', JSON.parse(uni.getStorageSync('location'))?.location?.cityName)
    return JSON.parse(uni.getStorageSync('location'))?.location?.cityName || '杭州市'
  } catch (error) {
    return '杭州市'
  }
}

// 公共弹出框
import usePopup from '@/hooks/usePopup'
const { SkipPopupRef, receive, skipPopupData, handleClose } = usePopup()
</script>

<template>
  <view class="box">
    <!-- 上部分模块 -->
    <view class="topModule">
      <view
        class="headerSearchBar"
        :style="{ paddingTop: Number(phoneStore?.phoneInfo?.top) + 3 + 'px' }"
      >
        <!-- logo -->
        <view class="image">
          <image src="/static/images/logo_.png" mode="scaleToFill" />
        </view>
      </view>
      <!-- 设备名称以及收藏设备 -->
      <view class="deviceName">
        <view @tap.stop="skipMapPage()" class="_machineName">
          {{ deviceStore.deviceInfo ? deviceStore.deviceInfo?.machineName : getCityName() }}
          <view class="iconfont icon_arrow-left-1"> </view>
        </view>
        <view
          v-if="deviceStore.deviceInfo?.businessStatus"
          class="_businessStatus"
          :class="{ trueStatus: deviceStore.deviceInfo?.businessStatus === '运营中' }"
          >{{ deviceStore.deviceInfo && deviceStore.deviceInfo?.businessStatus }}
        </view>
        <view
          @tap.stop="onCollect()"
          :style="{ top: Number(phoneStore.phoneInfo?.bottom) + 5 + 'px' }"
          class="_collection iconfont"
          :class="choiceIcon"
        >
        </view>
      </view>

      <!-- 设备距离 -->
      <view class="_length">
        <text class="iconfont icon_Frame-11"></text>
        <text class="text">
          {{ SwitchingDistance(`${deviceStore.deviceInfo?.distanceCenterPoint}m`) }}</text
        >
        <text
          class="iconfont icon_countDown"
          v-if="deviceStore.deviceInfo?.saleBeginTime && deviceStore.deviceInfo?.saleEndTime"
          >{{
            ` ${deviceStore.deviceInfo?.saleBeginTime}-${deviceStore.deviceInfo?.saleEndTime}`
          }}</text
        >
      </view>
      <view class="productionBox" v-if="awaitNum"
        >前方
        <view class="_num" :style="{ color: awaitNum > 10 ? '#FFBD2C' : '#FFBD2C' }">
          {{ awaitNum }}</view
        >
        份制作中</view
      >
      <view class="productionBox" v-else>现在下单，立即制作</view>
      <!-- 循环提示 弹出层 -->
      <view class="tips">
        <text class="iconfont icon_Frame1"></text>
        <text>{{ '用心做好每一顿饭，让人们吃的更健康' }}</text>
        <text v-if="false" class="iconfont icon_arrow-left"></text>
      </view>
    </view>
    <!-- 分类 -->
    <view class="sort">
      <!-- 右侧菜品栏 二级分类 -->

      <scroll-view scroll-y @scroll="scroll" :show-scrollbar="false" class="rightGoods_scroll">
        <!-- 首图 -->
        <view class="_image">
          <BjsSwiper
            @goToLogin="popupRef?.open"
            :list="imageList"
            :flag="false"
            :borderRradius="true"
          />
        </view>
        <!-- 每个类别盒子 -->
        <view class="itemBox" v-if="handleShow">
          <!-- 循环 item -->
          <BjsGoodsItem
            v-for="item in couponPackList"
            @goPay="goToPay"
            @triggerRules="triggerRules"
            :key="item.id"
            :goods="false"
            :item="item"
          />
          <BjsGoodsItem v-for="item in searchData" :key="item.comboId" :item="item" />
        </view>
        <view class="dontGoods" v-else>
          <image class="_image" src="/static/images/dontDoods.png" mode="scaleToFill" />
          <view class="dontGoodsText">
            <text>餐品已售空~</text>
            <text>请选择其他设备下单哦~</text>
          </view>
          <navigator
            class="skpiMap"
            url="/pagesEat/deviceSearch/deviceSearch"
            hover-class="view-hover"
            open-type="navigate"
            >更换设备
          </navigator>
        </view>
      </scroll-view>
    </view>
    <!-- 购物车悬浮球 -->
    <view class="cart" :class="{ spread: cartFlag }">
      <view class="cartImageBox">
        <image
          class="cartImage"
          @tap="onUnfold"
          src="/static/images/eat/gouwuche.png"
          mode="scaleToFill"
        >
        </image>
        <BjsCornerMark :value="com" />
      </view>

      <view class="sumPriceBox" v-if="shoppingCartStore.shoppingCartInfo.length > 0 && cartFlag">
        <view class="sumPrice">
          <view class="sumPrice_1">预估</view>
          <view class="sumPrice_2">￥{{ Number(totalPrice - discountMoney).toFixed(2) }}</view>
          <view
            class="sumPrice_3"
            v-show="Number(totalPrice - discountMoney).toFixed(2) !== Number(totalPrice).toFixed(2)"
            >￥{{ Number(totalPrice).toFixed(2) }}</view
          >
        </view>
        <text class="_text">已享受更低优惠，共减免￥{{ discountMoney.toFixed(2) }}</text>
      </view>
      <view class="dontData" v-if="shoppingCartStore.shoppingCartInfo.length <= 0 && cartFlag">
        <text>预估</text>
        <text class="price">￥0</text>
      </view>
      <view
        @tap.stop="goToPay()"
        v-if="cartFlag"
        :class="{ activeGoToPay: shoppingCartStore.shoppingCartInfo?.length }"
        class="checkoutButton"
        >{{ shoppingCartStore.shoppingCartInfo?.length ? '去结算' : '不可结算' }}</view
      >
    </view>
    <!-- 购物车弹出层 -->
    <uni-popup :safe-area="false" class="cartPopup" type="bottom" ref="cartPopup">
      <view class="cartPopupBox">
        <!-- 上面全选和删除 清空购物车 -->
        <view class="topText">
          <view class="all" v-if="false">
            <view class="iconfont icon_weixuanzhong"></view>
            <view>全选</view>
          </view>
          <view class="close" @tap.stop="onCloseCart()">
            <view class="closeIcon iconfont icon_shanchu4"></view>
            <view>清空</view>
          </view>
        </view>
        <!-- 中间套餐信息列表 -->
        <scroll-view
          class="scrollItemBox"
          scroll-y
          :enhanced="true"
          :bounces="true"
          :show-scrollbar="false"
        >
          <view
            class="item"
            v-for="item in shoppingCartStore.shoppingCartInfo"
            :key="item.packageId"
          >
            <image class="_image" :src="item.thumbUrl" mode="scaleToFill" />
            <view class="itemText">
              <view class="nameWrapper">
                <view class="_name1">{{ item.packageName }}</view>
                <view class="imageWrapper" v-if="item.spicy">
                  <image
                    v-for="(i, index) in item.spicy - 1"
                    :key="index"
                    class="image"
                    src="/static/images/Frame.png"
                  />
                  <image
                    v-for="(i, index) in 4 - item.spicy"
                    :key="index"
                    class="image"
                    src="/static/images/Frame2.png"
                  />
                </view>
              </view>
              <view class="_name2"> 已选：{{ item.packageName }} | 餐具 </view>
              <view class="_name3">
                <view class="discountPrice"> ￥ {{ Number(item.deviceAmount).toFixed(2) }} </view>
                <!-- <view class="originalPrice"> ￥ {{ Number(item.deviceAmount).toFixed(2) }} </view> -->
              </view>
            </view>
            <view class="_button">
              <text
                class="iconfont icon_reduce"
                @tap.stop="item.count > 1 ? item.count-- : onOpen(item.packageId)"
              ></text>
              <text class="">{{ item.count }}</text>
              <text
                class="iconfont icon_add"
                :class="{ active: item.count === item.inventory }"
                @tap.stop="item.count < item.inventory ? item.count++ : null"
              ></text>
            </view>
          </view>
        </scroll-view>
        <view class="placeholder"> </view>
      </view>
    </uni-popup>
    <!-- 设备 弹出层 -->
    <uni-popup
      class="S_popup"
      :safe-area="false"
      @change="devicePopupChange"
      ref="popup"
      type="bottom"
    >
      <view class="topTitle">
        <text class="topTitle_text">请确认取餐机</text>
        <view>您附近取餐机器较多，请确认取餐机器</view>
        <text @tap="popup?.close()" class="iconfont icon_close"></text>
      </view>
      <view style="background-color: #f5f6f7">
        <scroll-view scroll-y enhanced style="max-height: 60vh" :show-scrollbar="false">
          <view class="s_List">
            <BjsSpotItem
              @close="popup?.close()"
              @myClick="onClick"
              @collect="collectFn"
              v-if="machineList?.length"
              :list="machineList"
            />
            <view v-else>
              <image class="dontSpot" src="/static/images/meiyou.png" mode="scaleToFill" />
              <view class="dontSpotText">您的附近暂时还没有设备哦~</view>
            </view>
            <navigator
              @tap="popup?.close()"
              hover-class="none"
              url="/pagesEat/deviceSearch/deviceSearch"
              class="more"
              >选择其他设备<text class="iconfont icon_arrow-left-1"></text>
            </navigator>
          </view>
        </scroll-view>
      </view>
    </uni-popup>
    <!-- 登录弹出层 -->
    <BjsPopup ref="popupRef" />
    <!-- 优惠券商品 -->
    <BjsCouponPackPopup
      ref="rulePopupRef"
      :rules="{
        rule: rulePopupObj.declare,
      }"
      :item="rulePopupObj"
      @goPay="goToPay(rulePopupObj)"
    />
  </view>
  <BjsSkipPopup
    :img="skipPopupData.img"
    ref="SkipPopupRef"
    @receive="receive"
    @close="handleClose"
  />
</template>

<style lang="scss" scoped>
page {
  background-color: #f5f5f5;
  height: 100%;
  display: flex;
  flex-direction: column;
}
.box {
  height: 100%;
  display: flex;
  flex-direction: column;
}
.topModule {
  background-color: #fff;
  padding-bottom: 12rpx;
}
// 自定义导航栏
.headerSearchBar {
  display: flex;
  justify-content: space-between;
  background-color: #fff;
  .image {
    width: 200rpx;
    height: 64rpx;
    margin-left: 24rpx;
    image {
      width: 200rpx;
      height: 64rpx;
    }
  }
  .iconfont {
    width: 56rpx;
    height: 56rpx;
    line-height: 56rpx;
    text-align: center;
    border-radius: 50%;
    background-color: #f2f2f2;
    font-size: 32rpx;
  }
}
// 设备名称
.deviceName {
  display: flex;
  margin: 16rpx 0 8rpx 24rpx;
  height: 40rpx;
  line-height: 40rpx;
  font-size: 30rpx;
  color: #000000e5;
  background-color: #fff;
  font-weight: bold;
  ._machineName {
    display: flex;
    min-width: 100rpx;
    // align-items: center;
    .icon_arrow-left-1 {
      margin-right: 0;
      margin-left: 8rpx;
      height: 20rpx;
      line-height: 42rpx;
      font-size: 30rpx;
      color: #000000;
    }
    .iconfont {
      font-size: 20rpx;
    }
  }
  ._businessStatus {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 88rpx;
    line-height: 40rpx;
    margin-left: 20rpx;
    font-size: 20rpx;
    border-radius: 36rpx;
    background-color: $uni-color-motif;
    color: #fff;
  }
  .trueStatus {
    color: $uni-color-motif;
    border: 1px solid #daf4c9;
    background-color: #f1ffee;
  }
  ._collection {
    position: absolute;
    right: 30rpx;
    color: #0000004d;
    font-size: 42rpx;
  }
  .icon_XingX_1 {
    color: #fdcb4a;
  }
}
// 设备距离
._length {
  margin-left: 24rpx;
  height: 30rpx;
  line-height: 30rpx;
  font-size: 22rpx;
  color: #00000080;
  background-color: #fff;
  .iconfont {
    font-size: 28rpx;
  }
  .text {
    margin-left: 10rpx;
    margin-top: 48rpx;
  }
  .icon_countDown {
    margin-left: 24rpx;
    font-size: 24rpx;
  }
}
// 制作提示
.productionBox {
  display: flex;
  width: 100%;
  height: 40rpx;
  line-height: 40rpx;
  background-color: #fff;
  padding-left: 20rpx;
  color: #000;
  font-size: 24rpx;
  ._num {
    font-size: 34rpx;
  }
}
// 提示信息
.tips {
  position: relative;
  margin: 20rpx 24rpx 0;
  padding: 0 16rpx 0 62rpx;
  width: 700rpx;
  height: 60rpx;
  line-height: 60rpx;
  font-size: 24rpx;
  border-radius: 8rpx;
  color: $uni-color-motif;
  background-color: rgba(255, 189, 39, 0.15);
  .icon_Frame1 {
    position: absolute;
    line-height: 56rpx;
    left: 18rpx;
    font-size: 32rpx;
  }
  .icon_arrow-left {
    position: absolute;
    font-size: 20rpx;
    top: 2rpx;
    right: 16rpx;
  }
}
// 分类
.sort {
  flex: 1;
  display: flex;
  margin-top: 12rpx;
  .rightGoods_scroll {
    height: 77.33vh;
    padding: 16rpx 24rpx 94rpx;
    width: 100%;
    overflow: hidden;
    background-color: #fff;
    ::-webkit-scrollbar {
      //隐藏scroll-view里面自带的滚动条
      display: none; //必加
      width: 0 !important;
      height: 0 !important;
      -webkit-appearance: auto !important;
      background: transparent;
      overflow: auto !important;
    }
    ._image {
      border-radius: 24rpx;
      width: 702rpx;
      height: 236rpx;
      margin-bottom: 24rpx;
      background: #fff;
    }

    .itemBox {
      display: flex;
      flex-direction: column;
      width: 702rpx;
      padding-bottom: 100rpx;
      align-items: flex-end;
      .text {
        margin: 32rpx 0 24rpx 0;
        height: 36rpx;
        font-size: 26rpx;
        color: #000000e5;
      }
    }
  }
}
// 购物车悬浮球
.cart {
  position: fixed;
  bottom: 20rpx;
  right: 24rpx;
  display: flex;
  z-index: 98;
  border-radius: 50%;
  box-shadow: 0px 8rpx 16rpx rgba(0, 0, 0, 0.2);
  width: 104rpx;
  height: 104rpx;
  align-items: center;
  justify-content: center;
  .cartImageBox {
    width: 104rpx;
    height: 104rpx;
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .cartImage {
    position: relative;
    width: 48rpx;
    height: 48rpx;
  }
}
.spread {
  transition: width, height, border-radius, background-color, box-shadow;
  transition-duration: 50ms;
  width: 702rpx;
  height: 100rpx;
  border-radius: 50rpx;
  background-color: #fff;
  box-shadow: 0 4rpx 16rpx 0 rgba(0, 0, 0, 0.1);
  align-items: center;
  justify-content: flex-start;
  .cartImage {
    margin: 0 30rpx;
    width: 48rpx;
    height: 48rpx;
    z-index: 99;
  }
}
// 打开展示的信息
.sumPriceBox {
  display: flex;
  flex-direction: column;
  margin-left: 12rpx;
  font-size: 22rpx;
  color: #000000e5;
  .sumPrice {
    display: flex;
    align-items: center;
    .sumPrice_2 {
      height: 44rpx;
      margin: 0 8rpx 0 4rpx;
      font-size: 32rpx;
      color: #f14b4b;
    }
    .sumPrice_3 {
      text-decoration: line-through;
      color: #00000080;
    }
  }
  .sumPriceBox ._text {
    color: #00000080;
  }
}
.dontData {
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 22rpx;
  color: #000000e5;
  .price {
    font-size: 32rpx;
    color: #f14b4b;
  }
}
.checkoutButton {
  position: absolute;
  display: flex;
  justify-content: center;
  align-items: center;
  right: 0;
  width: 184rpx;
  height: 100rpx;
  font-size: 30rpx;
  color: #fff;
  border-radius: 0 50rpx 50rpx 0;
  background-color: rgba(255, 189, 39, 0.5);
  z-index: 9999;
}
// 去结算高亮
.activeGoToPay {
  background-color: $uni-color-motif;
}

// 弹出层
.S_popup {
  z-index: 99;
  .topTitle {
    position: relative;
    width: 100%;
    height: 140rpx;
    padding: 28rpx 32rpx;
    font-size: 24rpx;
    border-radius: 32rpx 32rpx 0px 0px;
    color: #00000080;
    background-color: #fff;
    .topTitle_text {
      margin-bottom: 8rpx;
      height: 42rpx;
      font-size: 30rpx;
      color: #000000e5;
    }
    .iconfont {
      position: absolute;
      top: 40rpx;
      right: 36rpx;
    }
  }
  .s_List {
    min-height: 100%;
    padding: 24rpx 36rpx;
    display: flex;
    flex-direction: column;
    // justify-content: center;
    align-items: center;
    box-sizing: border-box;
    background-color: #f5f6f7;
    .dontSpot {
      margin-top: 40rpx;
      width: 336rpx;
      height: 220rpx;
    }
    .dontSpotText {
      margin-top: 10rpx;
      font-size: 28rpx;
      color: #808080;
    }
  }
  .more {
    margin-top: 20rpx;
    width: 100%;
    text-align: center;
    font-size: 30rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #00000080;
    .iconfont {
      margin-left: 8rpx;
      font-size: 20rpx;
    }
  }
}
// 购物车弹出层
.cartPopup {
  z-index: 1; // 控制弹出层级
}
.topText {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 0 32rpx;
  width: 100%;
  height: 80rpx;
  border-radius: 32rpx 32rpx 0 0;
  background: #f5f6f7;

  .all {
    display: flex;
    font-size: 26rpx;
    color: #000000e5;
    .iconfont {
      margin-right: 12rpx;
      font-size: 32rpx;
      color: #0000004d;
    }
  }
  .close {
    display: flex;
    font-size: 22rpx;
    color: #00000080;
    .iconfont {
      margin-right: 8rpx;
      font-size: 28rpx;
    }
  }
}
.placeholder {
  width: 100%;
  height: 144rpx;
  background-color: #fff;
}
// 弹出层的套餐信息列表
.scrollItemBox {
  max-height: 40vh;
  padding: 24rpx 32rpx;
  background-color: #fff;
  padding-bottom: 0;
  ::-webkit-scrollbar {
    //隐藏scroll-view里面自带的滚动条
    display: none; //必加
    width: 0 !important;
    height: 0 !important;
    -webkit-appearance: auto !important;
    background: transparent;
    overflow: auto !important;
  }
}
.item {
  display: flex;
  align-items: center;
  position: relative;
  margin-bottom: 38rpx;
  // &:last-child {
  //   margin-bottom: 0;
  // }
  .item .iconfont {
    font-size: 32rpx;
    color: #0000004d;
  }
  .itemText {
    display: flex;
    flex: 1;
    margin-right: 166rpx;
    flex-direction: column;
    white-space: nowrap; /* 不换行 */
    overflow: hidden; /* 超出部分隐藏 */
    text-overflow: ellipsis; /* 显示省略号 */
    .nameWrapper {
      display: flex;
      justify-content: flex-start;
      align-items: center;
      ._name1 {
        font-size: 30rpx;
        color: #000000e5;
        white-space: nowrap; /* 不换行 */
        overflow: hidden; /* 超出部分隐藏 */
        text-overflow: ellipsis; /* 显示省略号 */
      }
      .imageWrapper {
        flex-shrink: 0;
        flex-grow: 1;
        min-width: 72rpx;
        margin-left: 4rpx;
        display: flex;
        .image {
          width: 24rpx;
          height: 24rpx;
        }
      }
    }
    ._name2 {
      font-size: 22rpx;
      color: #00000080;
      margin-bottom: 8rpx;
      white-space: nowrap; /* 不换行 */
      overflow: hidden; /* 超出部分隐藏 */
      text-overflow: ellipsis; /* 显示省略号 */
    }
    ._name3 {
      display: flex;
      align-items: center;
      font-size: 28rpx;
      color: #000000e5;
      .originalPrice {
        font-size: 22rpx;
        color: #0000004d;
        text-decoration: line-through;
      }
    }
  }
  ._image {
    width: 150rpx;
    height: 100rpx;
    margin: 0 20rpx;
    border-radius: 8rpx;
    background-color: #ccc;
  }
  ._button {
    position: absolute;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 146rpx;
    font-size: 28rpx;
    .iconfont {
      display: flex;
      justify-content: center;
      align-items: center;
      box-sizing: border-box; // 控制边框不超出盒子大小
      width: 44rpx;
      height: 44rpx;
      border-radius: 50%;
    }
    .icon_reduce {
      color: $uni-color-motif;
      border: 4rpx solid $uni-color-motif;
      background-color: #fff;
    }
    .icon_add {
      color: #fff;
      background-color: $uni-color-motif;
    }
    .active {
      color: #fff;
      border: 4rpx solid #ccc;
      background-color: #ccc;
    }
  }
}
// 清空购物车弹出层
.uni-popup {
  width: 600rpx;
  height: 304rpx;
  border-radius: 16rpx;
  font-size: 32rpx;
  color: #000000e5;
  background-color: #fff;
  z-index: 999; // 弹出层层级最高
  .uni-popup-top {
    display: flex;
    justify-content: space-around;
    flex-direction: column;
    align-items: center;
    height: 192rpx;
    border-bottom: 1px solid #ccc;
    padding: 62rpx 60rpx 32rpx;
  }
  .uni-popup-button {
    position: relative;
    height: 112rpx;
    display: flex;
    justify-content: space-around;
    align-items: center;
    .confirm {
      color: $uni-color-motif;
    }
    .line {
      position: absolute;
      top: 1rpx;
      left: 50%;
      width: 1px;
      height: 100%;
      background-color: #ccc;
    }
  }
}
.dontGoods {
  margin-top: 80rpx;
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  font-size: 26rpx;
  .dontGoodsText {
    margin-top: 10rpx;
    color: var(--FontColor-light-50, rgba(0, 0, 0, 0.5));
    display: flex;
    flex-direction: column;
    align-items: center;
  }
  ._image {
    margin-top: 80rpx !important;
    width: 336rpx !important;
    height: 220rpx !important;
  }
  .skpiMap {
    margin-top: 20rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 280rpx;
    height: 76rpx;

    border-radius: 44rpx;
    color: #fff;
    background-color: $uni-color-motif;
  }
}
</style>
